package com.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wms.mapper.CityMapper;
import com.wms.pojo.City;
import com.wms.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements CityService {

    @Autowired
    private CityMapper cityMapper;

    @Override
    public List<City> getAllCity() {
        //查询所有，得到全部的集合
        List<City> list = cityMapper.selectList(null);
        //分出父类集合，和子类集合
        List<City> parents = list.stream().filter(parent -> parent.getParentId() == 0).toList();
        List<City> childrens = list.stream().filter(children -> children.getParentId() > 0).toList();

        //循环每一个顶级父类，来找到属于它的子类
        parents.forEach(parent->{
            findChildren(parent,childrens);
        });
        return parents;
    }

    //递归调用
    //给每个顶级父类，来找到它的子类，然后的递归调用，找到它子类的子类
    public void findChildren(City parent,List<City> childern){
        //找到属于它的子类
        List<City> childerns = childern.stream().filter(c -> Objects.equals(c.getParentId(), parent.getId())).toList();
        //如果不为空，就是找到了它的子类，就要找它的子类的的子类
        //如果为空就要跳出这个递归
        if (!CollectionUtils.isEmpty(childerns)){
            childerns.forEach(d->findChildren(d,childern));
        }
        //给父类来设置它的子类集合
        parent.setChildren(childerns);
    }
}
